package engine.asset
{
	import engine.core.*;
	import engine.loaders.*;
	import flash.system.*;
	
	public class RxAssetXML extends RxAsset
	{
		private var m_xml:XML;
		private static var s_type:int;

		public function RxAssetXML()
		{
			super(s_type);
			this.m_xml = null;
		}
		
		public static function Initialize() : void
		{
			s_type = RxAsset.RegisterType("xml", CreateFromXML);
		}
		
		public static function CreateFromXML(xml:XML, path:String) : RxAssetXML
		{
			var name:String = xml.@name;
			var url:String = xml.@url;
			url = RxUtilities.MergePath(path, url);
			
			return Create(url, name);
		}
		
		public static function Create(url:String, name:String) : RxAssetXML
		{
			var xml:RxAssetXML = GetByURL(url);
			if (xml != null)
			{
				xml.m_references = xml.m_references + 1;
				return xml;
			}
			
			xml = new RxAssetXML;
			xml.SetURL(url);
			xml.SetName(name);
			
			return xml;
		}
		
		override public function Load() : void
		{
			super.Load();
			switch(m_state)
			{
				case STATE_EMPTY:
				{
					m_loader = StartLoad(m_url, RxLoader.TYPE_TEXT, this.OnLoadComplete);
					m_state = STATE_LOADING;
					break;
				}
				case STATE_LOADING:
				{
					break;
				}
				case STATE_ERROR:
				{
					ExecuteCallbacks(false);
					break;
				}
				case STATE_READY:
				{
					ExecuteCallbacks(true);
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private function OnLoadComplete(callback:RxLoaderCallback) : void
		{
			if (callback.m_result == true)
			{
				m_size = callback.m_loader.GetSizeInBytes();
				this.m_xml = XML(callback.m_loader.GetText());
				m_state = STATE_READY;
				ExecuteCallbacks(true);
			}
			else
			{
				m_state = STATE_ERROR;
				ExecuteCallbacks(false);
			}
		}
		
		public static function GetByURL(url:String) : RxAssetXML
		{
			return RxAssetXML(_getByURL(url, s_type));
		}
		
		public function GetXML() : XML
		{
			return this.m_xml;
		}
	}
}